import express from 'express';
import { authenticateToken, isAdmin } from '../middleware/auth.js';
import Order from '../models/Order.js';
import Movie from '../models/Movie.js';

const router = express.Router();

// 创建订单（购票）
router.post('/', authenticateToken, async (req, res) => {
  try {
    const { movieId, quantity } = req.body;
    const movie = await Movie.findById(movieId);

    if (!movie) {
      return res.status(404).json({ message: '电影不存在' });
    }

    if (movie.remainingTickets < quantity) {
      return res.status(400).json({ message: '剩余票数不足' });
    }

    const totalPrice = movie.price * quantity;
    const order = new Order({
      userId: req.user.userId,
      movieId,
      quantity,
      totalPrice
    });

    movie.remainingTickets -= quantity;
    await movie.save();
    await order.save();

    res.status(201).json(order);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取用户订单历史
router.get('/', authenticateToken, async (req, res) => {
  try {
    const orders = await Order.find({ userId: req.user.userId })
      .populate({
        path: 'movieId',
        select: 'title showtime price'
      });

    // 转换数据结构以匹配前端期望的格式
    const formattedOrders = orders.map(order => ({
      _id: order._id,
      quantity: order.quantity,
      totalPrice: order.totalPrice,
      status: order.status,
      createdAt: order.createdAt,
      movie: {
        title: order.movieId.title,
        showtime: order.movieId.showtime,
        price: order.movieId.price
      }
    }));

    res.json(formattedOrders);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取订单详情
router.get('/:id', authenticateToken, async (req, res) => {
  try {
    const order = await Order.findById(req.params.id)
      .populate('movieId', 'title showtime price')
      .populate('userId', 'username');

    if (!order) {
      return res.status(404).json({ message: '订单不存在' });
    }

    // 验证用户权限
    if (order.userId._id.toString() !== req.user.userId && req.user.role !== 'admin') {
      return res.status(403).json({ message: '没有权限查看此订单' });
    }

    res.json(order);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 取消订单
router.post('/:id/cancel', authenticateToken, async (req, res) => {
  try {
    const order = await Order.findById(req.params.id);
    
    if (!order) {
      return res.status(404).json({ message: '订单不存在' });
    }

    // 验证用户权限
    if (order.userId.toString() !== req.user.userId && req.user.role !== 'admin') {
      return res.status(403).json({ message: '没有权限取消此订单' });
    }

    // 检查订单是否已经被取消
    if (order.status === 'cancelled') {
      return res.status(400).json({ message: '订单已经被取消' });
    }

    // 更新电影票数
    const movie = await Movie.findById(order.movieId);
    if (movie) {
      movie.remainingTickets += order.quantity;
      await movie.save();
    }

    // 更新订单状态
    order.status = 'cancelled';
    await order.save();

    res.json({ message: '订单已取消', order });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

export default router;